import React from "react";

import { Grid, Row, Col } from 'react-flexbox-grid';

import {Badge,Card,Alert,Select} from 'antd';

import PageContent from '../PageContent'

import { ajax ,showResultMessage,setStoreItem,getStoreItem} from '../common';

import {UIDataTableView,UIDataTreeView} from '../uicomponents/UIDataComponentView';

import UIFormView from '../uicomponents/UIFormView';

import UIForm from '../uicomponents/UIForm';

import UICardTabs from '../uicomponents/UICardTabs';

import UIIcon from '../uicomponents/UIIcon';

const {Option} = Select;

/**
 * 系统功能模块管理
 */
export default class SysModuleManageApp extends React.Component {
	render() {
		return (
			<PageContent {...this.props} pageInstance={this} >
				<SysModuleListPanle currentModule={this.props.currentModule}/>
			</PageContent>
		);
	}
}

/** 
 * 产品应用域选择
*/
class SysAppDomainSelect extends React.Component {

	constructor(props) {
		super(props);
        this.sysAppDomainList = [];
        this.state = {
            sysAppDomainList : [],
        };
	}


	renderAppDoamin = (appDomain) => {
		let color = "";
		if ('IN_USE' === appDomain.status) {
			color = 'processing'
		}
		else if ('CLOSED' === appDomain.status) {
			color = 'error'
		}

		return (<Badge status={color} style={{ marginLeft: 6 }} text={<span><i className={appDomain.icon + ' fa-fw'} />{appDomain.name}</span>} />)
	}

	handleSelect = (value, opt) => {
		const { sysAppDomainList } = this.state;
		setStoreItem('lastSelectSysAppDomainId', value);
		if (this.props.onSelectSysAppDomain) {
			sysAppDomainList.map(appDomain => {
				if(appDomain.id + '' === value){
					this.props.onSelectSysAppDomain(appDomain);
				}
			});
		}
    }
    
    componentDidMount(){
        ajax('SYSTEM/APP/getSystemDomain',{},(data => {
            this.setState({sysAppDomainList : data});
        }));
    }

	render() {
		const { sysAppDomainList } = this.state;
		return (
			<Select style={{ width: 250 }}
				onSelect={this.handleSelect}
				placeholder="请选择应用域"
				defaultValue={getStoreItem('lastSelectSysAppDomainId')}
			>
				{sysAppDomainList.map(appDomain => (
					<Option key={appDomain.id} value={appDomain.id + ''}>{this.renderAppDoamin(appDomain)}</Option>
				))}
			</Select>
		);
	}
}

/** 
 * 系统功能树形列表
*/
class SysModuleTreeListPanle extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			appDomain : props.appDomain,
		}
	}

	componentDidMount(){
		this._mounted = true;
	}

	componentWillUnmount(){
		this._mounted = false;
	}

	reload = (appDomain) => {

		if(appDomain === undefined){
			if (this.sysModuleTreeRef !== null && this._mounted === true) {
				setTimeout(() => {
					this.sysModuleTreeRef.loadData();
				});
			}
		}
		else{
			this.setState({appDomain : appDomain});
			if (this.sysModuleTreeRef !== null && this._mounted === true) {
				setTimeout(() => {
					this.sysModuleTreeRef.loadData();
				});
			}
		}
	}

	actionHandler = (actionEvent) => {
		const { appDomain } = this.state;
		const { addNewSysModuleFormRef, sysModuleTreeRef, moveSysModuleFormRef, selectSysModuleIds, selectSysModule } = this;
		const owner = this;
		
		return {
			refresh : () => {
				owner.reload();
			},
			addSysModule: () => {
				addNewSysModuleFormRef.openModal();
			},
			closeDialog: () => {
				addNewSysModuleFormRef.closeModal();
			},
			doOk: () => {
				addNewSysModuleFormRef.getFormData((formData) => {
					const result = {};
					formData.domainId = appDomain.id;
					ajax('SYSTEM/APP/saveSysModule', formData).then((data) => {
						if (data) {
							addNewSysModuleFormRef.closeModal();
							result.success = true;
							result.message = 'message.saveSuccess';
							owner.reload()
						}
					}).catch(function (reason) {
						result.success = false;
						result.message = reason;
					}).finally(() => {
						//console.log(result);
						showResultMessage(result);
					});
				});
			},
			deleteSysModule: () => {
				const result = {};
				ajax('SYSTEM/APP/deleteSysModule', { id: selectSysModule.id }, (data) => {
					result.success = true;
					result.message = 'message.deleteSuccess';
					owner.reload();
					showResultMessage(result);
					if (this.props.onSysModuleSelected) {
						this.props.onSysModuleSelected(null);
					}
				});
			},
			moveUp: () => {
				ajax('SYSTEM/APP/moveUpSysModule', { 'sysModuleId': selectSysModule.id }, (data) => {
					sysModuleTreeRef.loadData({}, false);
				});
			},
			moveDown: () => {
				ajax('SYSTEM/APP/moveDownSysModule', { 'sysModuleId': selectSysModule.id }, (data) => {
					sysModuleTreeRef.loadData({}, false);
				});
			},
			moveModule: () => {
				moveSysModuleFormRef.openModal();
			}
		};
	}

	moveSysModuleActionHandler = (actionEvent) => {
		
		const {  sysModuleTreeRef, moveSysModuleFormRef, selectSysModule } = this;
		
		return {
			closeDialog: () => {
				moveSysModuleFormRef.closeModal();
			},
			doOk: () => {
				moveSysModuleFormRef.getFormData((formData) => {
					const result = {};

					if (formData.parentModuleId != null) {
						selectSysModule.parentModuleId = formData.parentModuleId;
					}
					else {
						selectSysModule.parentModuleId = 0;
					}

					ajax('SYSTEM/APP/saveSysModule', selectSysModule).then((data) => {
						if (data) {
							moveSysModuleFormRef.closeModal();
							result.success = true;
							result.message = 'message.saveSuccess';
							sysModuleTreeRef.loadData({}, false);
						}
					}).catch(function (reason) {
						result.success = false;
						result.message = reason;
					}).finally(() => {
						//console.log(result);
						showResultMessage(result);
					});
				});
			},
		};
	}

	render() {

		const { currentModule} = this.props;

		const {appDomain} = this.state;

		if (appDomain !== null) {

			const sysModuleTreeProps = {
				actionGroupId: 'sysModuleActionGroup',
				dataUrl: 'SYSTEM/sysModuleTree/buildTree/',
				pathValue: appDomain.id,
                expandLevel: -1,
                currentModule : currentModule,
				bordered: true,
				title: appDomain.name,
				actionHandler: this.actionHandler,
				ref: (inst) => { this.sysModuleTreeRef = inst },
				onSelectChange: (selectRowKeys, node) => {
					if(node === undefined){
						return;
					}
					this.selectSysModuleIds = selectRowKeys;
					if (this.props.onSysModuleSelected && node !== undefined && node.props.dataRef.nodeConfigId === 'sysModule') {
						this.selectSysModule = node.props.dataRef.nodeData;
						this.props.onSysModuleSelected(node.props.dataRef.nodeData);
					}
				},
				setToolbarState: (topToolBar, selectSysModuleIds, node) => {

					if(node === undefined){
						return;
					}

					const nodeData = node !== undefined ? node.props.dataRef : null;

					if (nodeData !== undefined && nodeData.nodeConfigId === 'sysModule' && selectSysModuleIds !== null && selectSysModuleIds.length > 0) {
						topToolBar.enable('delete');
						topToolBar.enable('edit');
						topToolBar.enable('moveUp');
						topToolBar.enable('moveDown');
						topToolBar.enable('moveModule');
					}
					else {
						topToolBar.disable('delete');
						topToolBar.disable('edit');
						topToolBar.disable('moveUp');
						topToolBar.disable('moveDown');
						topToolBar.disable('moveModule');
					}
				}
			};

			const sysModuleFormProps = {
				formConfigId: 'sysModuleAddNewForm',
				title: '新增系统模块',
				actionGroupId: 'defaultDiaoligActionGroup',
				inPop: true,
				params : appDomain.id,
				destroyOnClose: true,
				actionHandler: this.actionHandler,
				ref: (inst) => { this.addNewSysModuleFormRef = inst },

			};

			const moveSysModuleFormProps = {
				formConfigId: 'sysModuleMoveForm',
				title: '移动系统模块',
				actionGroupId: 'defaultDiaoligActionGroup',
				inPop: true,
				params : {domainId : appDomain.id,disabledIds : [] } ,
				destroyOnClose: true,
				actionHandler: this.moveSysModuleActionHandler,
				ref: (inst) => { this.moveSysModuleFormRef = inst },
			};

			return (
				<React.Fragment>
					<UIDataTreeView {...sysModuleTreeProps} />
					<UIFormView {...sysModuleFormProps} />
					<UIFormView {...moveSysModuleFormProps} />
				</React.Fragment >
			);
		}
		else {
			return <div />
		}
	}
};

/** 
* 系统模块编辑表单
*/
class SysModuleEditFormPanel extends React.Component {

	setSysModule = (sysModule) => {
		this.formRef.setFormData(sysModule);
	}

	actionHandler = (actionEvent) => {
		const owner = this;
		return {
			doSave: () => {
				actionEvent.component.getFormData((formData) => {
					const result = {};
					ajax('SYSTEM/APP/saveSysModule', formData).then((data) => {
						if (data) {
							result.success = true;
							result.message = 'message.saveSuccess';
							if (owner.props.onSaveSysModule) {
								owner.props.onSaveSysModule(data);
							}
						}
					}).catch(function (reason) {
						result.success = false;
						result.message = reason;
					}).finally(() => {
						//console.log(result);
						showResultMessage(result);
					});
				});
			}
		}
	}

	render() {

		const sysModuleFormProps = {
			formConfigId: 'sysModuleEditForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
		};

		return (
			<UIForm {...sysModuleFormProps} wrappedComponentRef={(inst) => this.formRef = inst}>

			</UIForm>
		);
	}
}

/**
* 模块功能列表
 */
class SysModuleActionListPanel extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			title: '',
		}
	}


	setSysModule = (sysModule) => {
		this.sysModule = sysModule;
		this.tableRef.loadData({ moduleId: sysModule.id });
	}

	actionHandler = (actionEvent) => {
		const { sysModule, tableRef, formRef, selectedActionIds } = this;
		console.log(sysModule);
		const owner = this;
		return {
			addNew: () => {
				this.setState({ title: '新增模块功能' });
				setTimeout(() => {
					formRef.openModal();
				});
			},
			doEdit: (actionEvent) => {
				this.setState({ title: '编辑模块功能' });
				setTimeout(() => {
					formRef.openModal(() => {
						ajax('SYSTEM/APP/getSysActionById', { id: selectedActionIds[0] }, (data) => {
							formRef.setFormData(data);
						});
					});
				});
			},
			closeDialog: () => {
				formRef.closeModal();
			},
			doOk: (actionEvent) => {
				formRef.getFormData((formData) => {
					const result = {};

					formData.moduleId = sysModule.id;
					formData.domainId = sysModule.domainId;

					ajax('SYSTEM/APP/saveSysAction', formData).then((data) => {
						if (data) {
							result.success = true;
							result.message = 'message.saveSuccess';
							formRef.closeModal();
							tableRef.loadData({ moduleId: sysModule.id });
						}
					}).catch(function (reason) {
						result.success = false;
						result.message = reason;
					}).finally(() => {
						//console.log(result);
						showResultMessage(result);
					});
				});
			},
			deleteSysAction: () => {
				ajax('SYSTEM/APP/deleteSysAction', { ids: selectedActionIds }, (data) => {
					tableRef.loadData({ moduleId: sysModule.id });
				});
			}

		};
	}

	render() {

		const sysModuleActionListProps = {
			bordered: false,
			tableConfigId: 'systemModuleActionList',
			dataUrl: 'SYSTEM/APP/getSysActionByModuleId',
			selectMode: 'multi',
			actionGroupId: 'sysActionActionGroup',
			autoLoad: false,
			setSysModule: this.setSysModule,
			actionHandler: this.actionHandler,
			onSelectChange: (selectedIds) => {
				this.selectedActionIds = selectedIds;
			},
			setToolbarState: (topToolBar, selectedActionIds) => {
				if (selectedActionIds != null && selectedActionIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
		};

		const sysModuleActionFormProps = {
			formConfigId: 'sysActionForm',
			actionGroupId: 'defaultDiaoligActionGroup',
			inPop: true,
			title: this.state.title,
			destroyOnClose: true,
			actionHandler: this.actionHandler,
		};

		return (
			<React.Fragment>
				<UIDataTableView ref={inst => this.tableRef = inst} {...sysModuleActionListProps} />
				<UIFormView ref={inst => this.formRef = inst} {...sysModuleActionFormProps} />
			</React.Fragment>

		);
	}
}



/** 
 * 系统功能编辑
*/
class SysModuleInfoPanle extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
		}
	}

	onTabChange = (tabName) => {
		switch (tabName) {
			case 'sysModuleInfoEditorPart':
				this.sysModuleEditFormRef.setSysModule(this.sysModule);
				break;
			case 'sysModuleActionList':
				this.sysModuleActionListRef.setSysModule(this.sysModule);
				break;
		}
	}

	setSysModule = (sysModule) => {
		this.sysModule = sysModule;
		if (this.sysModuleEditFormRef != null) {
			this.sysModuleEditFormRef.setSysModule(sysModule);
		}
		if (this.sysModuleActionListRef != null) {
			this.sysModuleActionListRef.setSysModule(sysModule);
		}
	}


	render() {

		const tabPanelContentMap = {
            '/SysModuleEditFormPanel': {

                getComponent: (owner, props) => {
                    return <SysModuleEditFormPanel ref={(inst) => this.sysModuleEditFormRef = inst} onSaveSysModule={this.props.onSaveSysModule}/>;
                }
            },
            '/SysModuleActionListPanel': {

                getComponent: (owner, props) => {
                    return <SysModuleActionListPanel ref={(inst) => this.sysModuleActionListRef = inst} />
                }
            },

        };

		const configProps = {
			title: this.props.title,
			tabConfigId: 'sysModuleEditorTab',
			onTabChange: this.onTabChange,
			onSaveSysModule: this.props.onSaveSysModule,
			tabContentMap: tabPanelContentMap,
		};

		return (
			<UICardTabs {...configProps}>

			</UICardTabs>
		);
	}
}

/** 
 * 功能列表
*/
class SysModuleListPanle extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			appDomain: null,
			selectedModule: null
		}
	}

	componentDidMount() {
		if (getStoreItem('lastSelectSysAppDomainId')) {
			ajax('SYSTEM/APP/getSysDomainById', { id: getStoreItem('lastSelectSysAppDomainId') }, (data) => {
				this.onSelectSysAppDomain(data);
			});
		}
	}


	onSelectSysAppDomain = (selectedAppDoamin) => {
		this.setState({ appDomain: selectedAppDoamin ,selectedModule: null});
		setTimeout(() => {
			this.sysModuleTreeListRef.reload(selectedAppDoamin);
		},500);
	}

	onSysModuleSelected = (selectedSysModule) => {
		//console.log(selectedSysModule);
		this.setState({ selectedModule: selectedSysModule });
		if(selectedSysModule !== null){
            setTimeout(() => {
                this.sysModuleInfoRef.setSysModule(selectedSysModule);
            });
        }
	}

	onSaveSysModule = () => {
		this.sysModuleTreeListRef.reload(this.state.appDomain);
	}

	render() {
		const { appDomain, selectedModule } = this.state;
		return (
			<Card
				title={(appDomain != null ? <span><UIIcon icon={appDomain.icon}/>{'[' + appDomain.name + ']系统模块列表'}</span> : <span><UIIcon icon="question"/>{'请选择应用域'}</span>)}
				extra={<SysAppDomainSelect onSelectSysAppDomain={this.onSelectSysAppDomain}></SysAppDomainSelect>}
			>
				
				<Row >
					<Col xs>
						<SysModuleTreeListPanle
                            currentModule={this.props.currentModule}
							appDomain={appDomain}
							ref={(inst) => this.sysModuleTreeListRef = inst}
							onSysModuleSelected={this.onSysModuleSelected}
						/>
					</Col>

					<Col xs>
						{
							selectedModule != null ? <SysModuleInfoPanle title={<span><i className={selectedModule.moduleIcon + ' fa-fw'} /> {selectedModule.moduleName}</span>} ref={(inst) => this.sysModuleInfoRef = inst} onSaveSysModule={this.onSaveSysModule} /> :
								<Alert message="请选择系统模块,查看模块信息" type="info" showIcon />
						}
					</Col>
				</Row>
			    
			</Card>

		);
	}
}